package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import static com.itheima.constant.MessageConstant.QUERY_CHECKGROUP_FAIL;

@RestController
@RequestMapping("checkGroup")
public class CheckGroupController {

    @Reference(version = "1.0")
    CheckGroupService checkGroupService;
    @Autowired
    JedisPool jedisPool;

    @PostMapping("/save")
    public Result save(@RequestBody CheckGroup checkGroup){
        return checkGroupService.save(checkGroup);
    }

    @PostMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean){
        return checkGroupService.findPage(queryPageBean);
    }

    @GetMapping("/findById")
    public Result findById(Integer checkGroupId){
        return checkGroupService.findById(checkGroupId);
    }

    @PostMapping("/update")
    public Result update(@RequestBody CheckGroup checkGroup){
        return checkGroupService.update(checkGroup);
    }

    @GetMapping("/delete")
    public Result delete(Integer id){
        return checkGroupService.delete(id);
    }

    @GetMapping("/findAllCheckGroup")
    public Result findAllCheckGroup( ){
        try (Jedis jedis = jedisPool.getResource()) {
            String checkgroup_all = jedis.get("checkgroup_all");
            if (StringUtils.isNotBlank(checkgroup_all)) {
                return JSON.parseObject(checkgroup_all, Result.class);
            }
            Result allCheckGroup = checkGroupService.findAllCheckGroup();
            jedis.setex("checkgroup_all",5*60, JSON.toJSONString(allCheckGroup));
            //设置过期时间
            return allCheckGroup;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(500,QUERY_CHECKGROUP_FAIL);
    }
}
